<template>
  <div class="add">
    <el-button type="primary" size="small" :icon="Plus" @click="addDiaryType"
      >新增分类</el-button
    >
  </div>

  <el-table :data="tableData" style="width: 100%">
    <el-table-column label="分类名称" prop="name" align="center" />
    <el-table-column label="描述" prop="des" align="center" />
    <el-table-column label="是否推荐" prop="hot" align="center">
      <template #default="scope">
        <el-switch disabled v-model="scope.row.hot" />
      </template>
    </el-table-column>
    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
          >编辑</el-button
        >
        <el-popconfirm title="确定删除?" @confirm="handleDelete(scope.row.id)">
          <template #reference>
            <el-button size="small" type="danger"> 删除 </el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
    v-model:currentPage="currentPage"
    :page-sizes="pageSizeDefault"
    :page-size="pageSize"
    small
    background
    layout="total, sizes, prev, pager, next, jumper"
    :total="totalLength"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />

  <el-dialog
    v-model="dialogVisible"
    :title="butTypeVisible ? '更新分类' : '新增分类'"
  >
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
    >
      <el-form-item label="分类名称：" prop="name">
        <el-input v-model="ruleForm.name" placeholder="请输入分类名称" />
      </el-form-item>
      <el-form-item label="分类描述：" prop="des" show-overflow-tooltip>
        <el-input
          v-model="ruleForm.des"
          :rows="4"
          type="textarea"
          placeholder="请输入分类描述"
        />
      </el-form-item>
      <el-form-item label="是否推荐：" prop="hot">
        <el-switch v-model="ruleForm.hot" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button v-if="!butTypeVisible" @click="submitForm(ruleFormRef)"
          >新增</el-button
        >
        <el-button v-else @click="updateSubmitForm(ruleFormRef)"
          >更新</el-button
        >
        <el-button type="primary" @click="closeForm">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { WorksType } from "@/api/type";
import {
  getDiaryTypeInfo,
  addDiaryTypeInfo,
  updateDiaryTypeInfo,
  delDiaryTypeInfo,
} from "@/api/index";

const tableData = ref([] as WorksType);
const dialogVisible = ref(false);
const butTypeVisible = ref(false);
const ruleFormRef = ref();
const ruleForm = reactive({
  id: undefined,
  name: "",
  des: "",
  hot: false,
} as WorksType[]);
const rules = reactive({
  name: [
    {
      required: true,
      message: "请输入分类名称",
      trigger: "change",
    },
  ],
});
const currentPage = ref(1);
const pageSizeDefault = ref([5, 10, 20, 40]);
const pageSize = ref(5);
const totalLength = ref();

// 清空数据
const initRuleFrom = () => {
  ruleForm.id = undefined;
  ruleForm.name = "";
  ruleForm.des = "";
  ruleForm.hot = false;
};
// 每页显示多少条
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  initDiaryTypeInfo();
};
//点击中间页的按钮 执行的方法
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  initDiaryTypeInfo();
};
// 获取数据
const initDiaryTypeInfo = async () => {
  const res = await getDiaryTypeInfo(currentPage.value, pageSize.value);
  if (res) {
    res.worksList.forEach((item) => {
      item.hot = item.hot !== 0;
    });
    totalLength.value = res.totalNumber;
    tableData.value = res.worksList;
  }
};
//提交新增的数据
const submitForm = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const res = await addDiaryTypeInfo(ruleForm);
      if (res.code === 200) {
        ElMessage.success(res.msg);
        dialogVisible.value = false;
        initRuleFrom();
        initDiaryTypeInfo();
      } else {
        ElMessage.error(res.msg);
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
// 关闭对话框
const closeForm = () => {
  initRuleFrom();
  dialogVisible.value = false;
};
// 开启对话框
const addDiaryType = () => {
  initRuleFrom();
  dialogVisible.value = true;
  butTypeVisible.value = false;
};
// 编辑
const handleEdit = async (index: number, row) => {
  dialogVisible.value = true;
  butTypeVisible.value = true;
  ruleForm.id = row.id;
  ruleForm.name = row.name;
  ruleForm.des = row.des;
  ruleForm.hot = row.hot;
};
// 更新数据
const updateSubmitForm = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const res = await updateDiaryTypeInfo(ruleForm);
      if (res.code === 200) {
        ElMessage.success(res.msg);
        dialogVisible.value = false;
        initRuleFrom();
        initDiaryTypeInfo();
      } else {
        ElMessage.error(res.msg);
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
//删除数据
const handleDelete = async (id: number) => {
  const res = await delDiaryTypeInfo(id);
  if (res.code === 200) {
    ElMessage.success(res.msg);
    dialogVisible.value = false;
    initRuleFrom();
    initDiaryTypeInfo();
  } else {
    ElMessage.error(res.msg);
  }
};

onMounted(() => {
  initDiaryTypeInfo();
});
</script>

<style lang="scss" scoped>
.add {
  margin-bottom: 10px;
}
</style>
